import { Injectable } from '@nestjs/common';
import axios from 'axios';
import config from 'src/config';
import { InjectRepository } from '@nestjs/typeorm';
import { Mproduct } from './entities/mproduct.entity';
import { Repository } from 'typeorm';
import { ResponseService } from 'src/response/response.service';
import { Mcustomer } from './entities/mcustomer.entity';
import { Mbill } from './entities/mbilling.entity';
import { BillingDetails } from './entities/mbillingdetail.entity';
import { CreateMbillDto } from './dto/create-mbilling.dto';
import { SimplePaginatedResponse } from 'src/common/dto/pagination.dto';

@Injectable()
export class MadeService {
  constructor(
    @InjectRepository(Mproduct) private readonly mproduct: Repository<Mproduct>,
    @InjectRepository(Mcustomer)
    private readonly mcustomer: Repository<Mcustomer>,
    @InjectRepository(Mbill) private readonly mbill: Repository<Mbill>,
    @InjectRepository(BillingDetails)
    private readonly billdetail: Repository<BillingDetails>,
    private readonly responseService: ResponseService,
  ) {}

  create() {
    return 'This action adds a new made';
  }

  findAll() {
    const result = this.mbill.find();
    return this.responseService.createSuccessResponse(result);
  }

  async searchByKeyword(
    keyword: string,
    page: number = 1,
    limit: number = 50,
  ): Promise<SimplePaginatedResponse<Mbill>> {
    const pageNum = Math.max(1, Math.min(page, 2147483647));
    const pageSize = Math.max(1, Math.min(limit, 1000));
    const skip = (pageNum - 1) * pageSize;

    const [data, total] = await this.mbill
      .createQueryBuilder('mbill')
      .where('Customer LIKE :keyword', { keyword: `%${keyword}%` })
      .orWhere('OrderNumber LIKE :keyword', { keyword: `%${keyword}%` })
      .orderBy('Date', 'DESC')
      .skip(skip)
      .take(pageSize)
      .getManyAndCount();

    return {
      data,
      total,
      page: pageNum,
      limit: pageSize,
    };
  }

  async findOne(id: string) {
    const mbill = await this.mbill.findOne({
      where: { OrderNumber: id },
      relations: ['billingDetails'],
    });

    if (!mbill) {
      return this.responseService.createErrorResponse(
        '404',
        `Order with ID ${id} not found`,
      );
    }

    return this.responseService.createSuccessResponse(mbill);
  }

  update(id: number) {
    return `This action updates a #${id} made`;
  }

  remove(id: number) {
    return `This action removes a #${id} made`;
  }

  async generateImage(data) {
    const url = config.apiHost + config.apiEndpoint;
    const payload = {
      data,
    };
    try {
      const response = await axios.post(url, payload);
      return this.responseService.createSuccessResponse(response.data.data);
    } catch (error) {
      throw new Error(`Failed to make POST request: ${error.message}`);
    }
  }

  async searchProductByKeyword(keyword: string) {
    const quotes = await this.mproduct
      .createQueryBuilder('made_product')
      .select('made_product.ProductName')
      .where('made_product.ProductName LIKE :keyword', {
        keyword: `%${keyword}%`,
      })
      .distinct(true)
      .getMany();
    return this.responseService.createSuccessResponse(quotes);
  }

  async searchCustomerByKeyword(keyword: string) {
    const quotes = await this.mcustomer
      .createQueryBuilder('made_customer')
      .select('made_customer.CustomerName')
      .where('made_customer.CustomerName LIKE :keyword', {
        keyword: `%${keyword}%`,
      })
      .distinct(true)
      .getMany();
    return this.responseService.createSuccessResponse(quotes);
  }

  async createOrder(data: CreateMbillDto) {
    const {
      customername,
      ordernumber,
      totalOrderMoney,
      ReceivedAmount,
      OrderRemarks,
      list,
    } = data;

    let bill = await this.mbill.findOne({
      where: { OrderNumber: ordernumber },
    });
    console.log(bill);
    if (bill) {
      this.mbill.update(bill.Identify, {
        Customer: customername,
        Date: new Date(),
        OrderNumber: ordernumber,
        TotalAmount: totalOrderMoney,
        ReceivedAmount: ReceivedAmount || 0,
        OrderRemarks: OrderRemarks || '',
      });
    } else {
      bill = this.mbill.create({
        Customer: customername,
        Date: new Date(),
        OrderNumber: ordernumber,
        TotalAmount: totalOrderMoney,
        ReceivedAmount: ReceivedAmount || 0,
        OrderRemarks: OrderRemarks || '',
      });
      await this.mbill.save(bill);
    }

    // 先删除该订单号下所有旧的商品明细
    await this.billdetail.delete({ OrderNumber: ordernumber });

    // 再插入新的明细
    for (const item of list) {
      const {
        productname,
        unit,
        additionalfee,
        price,
        TotalMoney,
        TotalQuantity,
        nums,
      } = item;

      const billingDetail = this.billdetail.create({
        OrderNumber: ordernumber,
        Product: productname,
        Unit: unit,
        UnitPrice: price,
        TotalQuantity: TotalQuantity,
        TotalMoney: TotalMoney,
        AdditionalFee: additionalfee,
        Quantity1: nums?.Quantity1 ? Number(nums.Quantity1) : null,
        Quantity2: nums?.Quantity2 ? Number(nums.Quantity2) : null,
        Quantity3: nums?.Quantity3 ? Number(nums.Quantity3) : null,
        Quantity4: nums?.Quantity4 ? Number(nums.Quantity4) : null,
        Quantity5: nums?.Quantity5 ? Number(nums.Quantity5) : null,
        Quantity6: nums?.Quantity6 ? Number(nums.Quantity6) : null,
        Quantity7: nums?.Quantity7 ? Number(nums.Quantity7) : null,
        Quantity8: nums?.Quantity8 ? Number(nums.Quantity8) : null,
        Quantity9: nums?.Quantity9 ? Number(nums.Quantity9) : null,
        Quantity10: nums?.Quantity10 ? Number(nums.Quantity10) : null,
      });

      await this.billdetail.save(billingDetail);
    }

    return this.responseService.createSuccessResponse({
      message: '订单创建成功',
      orderNumber: ordernumber,
    });
  }

  async removeByOrderNumber(orderNumber: string) {
    const bill = await this.mbill.findOne({
      where: { OrderNumber: orderNumber },
    });

    if (!bill) {
      return this.responseService.createErrorResponse(
        '404',
        `Order with number ${orderNumber} not found`,
      );
    }

    await this.billdetail.delete({ OrderNumber: orderNumber });
    await this.mbill.delete({ OrderNumber: orderNumber });

    return this.responseService.createSuccessResponse({
      message: '订单删除成功',
    });
  }
}
